﻿using Castle.Core.Logging;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Yto.Common.Dependency;

namespace Yto.Common
{
    public static class FileHelper
    {
        private static ILogger Logger { get; set; }

        static FileHelper()
        {
            Logger = CtnManager.Instance.IsRegisted<ILoggerFactory>() ?
                CtnManager.Instance.Resolver<ILoggerFactory>().Create(typeof(FileHelper))
                : NullLogger.Instance;
        }
        /// <summary>
        /// 传入文件名称（全），若路径不存在则创建
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool CreateDirectory(string fileName)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(fileName);
                if (fileInfo != null && !fileInfo.Exists)
                {
                    FileInfo pathInfo = new FileInfo(fileInfo.DirectoryName);
                    if (!pathInfo.Exists)
                    {
                        Directory.CreateDirectory(pathInfo.FullName);
                    }
                    return true;
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
            return false;
        }

        /// <summary>
        /// 检查指定路径是否存在（未完成）
        /// </summary>
        /// <param name="pathName"></param>
        /// <returns></returns>
        public static bool DirectoryExist(string pathName)
        {
            try
            {
                DirectoryInfo dirInfo = new DirectoryInfo(pathName);
                if (dirInfo != null)
                {
                    return dirInfo.Exists;
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
            return false;
        }

        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool FileExist(string fileName)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(fileName);
                if (fileInfo != null)
                {
                    return fileInfo.Exists;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
            return false;
        }

        /// <summary>
        /// 复制文件
        /// </summary>
        /// <param name="source">源文件</param>
        /// <param name="destination">目标文件</param>
        public static bool CopyFile(string source, string destination)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(source);
                if (fileInfo.Exists)
                {
                    fileInfo.CopyTo(destination, true);
                    return true;
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
            return false;
        }

        /// <summary>
        /// 备份文件（按日期）
        /// </summary>
        /// <param name="fileName"></param>
        public static void BackupFile(string fileName)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(fileName);
                if (fileInfo.Exists)
                {
                    string backupName = fileName + "." + DateTime.Now.ToString("yyyy-MM-dd.HH-mm-ss");
                    fileInfo.CopyTo(backupName, true);
                }
                //fileInfo = null;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
        }

        /// <summary>
        /// 删除指定文件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool DeleteFile(string fileName)
        {
            try
            {
                File.Delete(fileName);
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
            return false;
        }

        /// <summary>
        /// 重命名文件
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destination"></param>
        /// <returns></returns>
        public static bool Rename(string source, string destination)
        {
            try
            {
                FileInfo fileInfo = new FileInfo(source);
                if (fileInfo.Exists)
                {
                    fileInfo.MoveTo(destination);
                }
                //fileInfo = null;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
            return false;
        }

        /// <summary>
        /// 将文件移至指定路径
        /// </summary>
        /// <param name="source"></param>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool Move2Path(string source, string path,bool isBak)
        {
            if (source == null || path == null)
                return false;
            int index = source.LastIndexOf('\\');
            if (index < -1 || index > source.Length)
            {
                return false;
            }
            string filename = source.Substring(index + 1);
            string destination = path;
            if (destination[path.Length - 1] != '\\')
            {
                destination += '\\';
            }
            destination += filename;
            try
            {
                FileInfo fileInfo = new FileInfo(source);
                if (fileInfo.Exists)
                {
                    if (FileExist(destination))
                    {
                        if (isBak)
                        {
                            BackupFile(destination);
                        }
                        if (DeleteFile(destination))
                        {
                            fileInfo.MoveTo(destination);
                        }
                    }
                    else
                    {
                        fileInfo.MoveTo(destination);
                    }
                }
                //fileInfo = null;
                return true;
            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
            return false;
        }
        //
        //        /// <summary>
        //        /// 文件文本过滤器
        //        /// </summary>
        //        /// <param name="sources">源文件</param>
        //        /// <param name="filters">过滤器</param>
        //        /// <param name="append">附加文件名</param>
        //        /// <returns>以TextFileFilterResult为元素的列表</returns>
        //        public static ArrayList TextFileFilter(string [] sources, string[] filters, string append) {
        //            ArrayList list = new ArrayList();
        //            if(sources!=null&&filters!=null&&filters.Length>0&&append!=null) {
        //                //                int total = sources.Length;
        //                //                int count = 0;
        //                foreach(string source in sources) {
        //                    TextFileFilterResult result = new TextFileFilterResult();
        //                    result.Filename = source;
        //                    int lastIndex = source.LastIndexOf('\\');
        //                    string path = source.Substring(0, lastIndex);
        //                    string dest = path + "\\" + append + source.Substring(lastIndex+1);
        //                    StreamReader sr = null;
        //                    StreamWriter sw = null;
        //                    try {
        //                        //Console.WriteLine("开始提取，源文件：{0}", source);
        //                        sr = new StreamReader(source);
        //                        sw = new StreamWriter(dest, false);
        //                        string line;
        //                        while((line = sr.ReadLine())!=null) {
        //                            foreach(string filter in filters) {
        //                                int index = line.IndexOf(filter);
        //                                if(index>0) {
        //                                    sw.WriteLine(line);
        //                                }
        //                            }
        //                        }
        //                        //Console.WriteLine("提取完毕，目标文件：{0}", dest);
        //                        //                        count++;
        //                    }catch(Exception ex) {
        //                        result.Exception = ex;
        //                        //Console.WriteLine("提取失败{0}", ex.Message);
        //                    }catch {
        //                        //Console.WriteLine("提取失败");
        //                    }
        //                    try {
        //                        if(sw!=null)
        //                            sw.Close();
        //                    }catch{}
        //                    try {
        //                        if(sr!=null)
        //                            sr.Close();
        //                    }catch{}                
        //                }
        //            }
        //            return list;
        //        }
        //
        //        /// <summary>
        //        /// 文件转换结果
        //        /// </summary>
        //        public class TextFileFilterResult {
        //
        //            private string filename;
        //            /// <summary>
        //            /// 文件名
        //            /// </summary>
        //            public string Filename {
        //                get { return filename; }
        //                set { filename = value; }
        //            }
        //
        //            private Exception exception;
        //            /// <summary>
        //            /// 异常，若为空则转换为空
        //            /// </summary>
        //            public Exception Exception {
        //                get { return exception; }
        //                set { exception = value; }
        //            }
        //
        //        }

        /// <summary>
        /// 文件文本过滤器
        /// </summary>
        /// <param name="source">源文件</param>
        /// <param name="filters">过滤器</param>
        /// <param name="append">附加文件名</param>
        /// <returns>转换结果</returns>
        public static bool TextFileFilter(string source, string[] filters, string append)
        {
            bool result = false;
            if (source != null && filters != null && filters.Length > 0 && append != null)
            {
                //                int total = sources.Length;
                //                int count = 0;
                int lastIndex = source.LastIndexOf('\\');
                string path = source.Substring(0, lastIndex);
                string dest = path + "\\" + append + source.Substring(lastIndex + 1);
                StreamReader sr = null;
                StreamWriter sw = null;
                try
                {
                    //Console.WriteLine("开始提取，源文件：{0}", source);
                    sr = new StreamReader(source);
                    sw = new StreamWriter(dest, false);
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        foreach (string filter in filters)
                        {
                            int index = line.IndexOf(filter);
                            if (index > 0)
                            {
                                sw.WriteLine(line);
                            }
                        }
                    }
                    //Console.WriteLine("提取完毕，目标文件：{0}", dest);
                    //                        count++;
                    result = true;
                }
                catch (Exception ex)
                {
                    //Console.WriteLine("提取失败{0}", ex.Message);
                }
                catch
                {
                    //Console.WriteLine("提取失败");
                }
                try
                {
                    if (sw != null)
                        sw.Close();
                }
                catch { }
                try
                {
                    if (sr != null)
                        sr.Close();
                }
                catch { }
            }
            return result;
        }

        public static FileInfo[] GetAllFile(string DirectoryPath)
        {
            try
            {
                DirectoryInfo dirInfo = new DirectoryInfo(DirectoryPath);
                if (dirInfo != null)
                {
                    return dirInfo.GetFiles();
                }

            }
            catch (Exception ex)
            {
                Logger.Error(ex.Message, ex);
            }
            return null;
        }

        /// <summary>
        /// 文件夹移动
        /// </summary>
        /// <param name="srcFolderPath"></param>
        /// <param name="destFolderPath"></param>
        public static void FolderMove(string srcFolderPath, string destFolderPath)
        {
            //检查目标目录是否以目标分隔符结束，如果不是则添加之
            if (destFolderPath[destFolderPath.Length - 1] != Path.AltDirectorySeparatorChar)
                destFolderPath += Path.AltDirectorySeparatorChar;
            //判断目标目录是否存在，如果不在则创建之
            if (!Directory.Exists(destFolderPath))
                Directory.CreateDirectory(destFolderPath);
            string[] fileList = Directory.GetFileSystemEntries(srcFolderPath);
            foreach (string file in fileList)
            {
                if (Directory.Exists(file))
                {
                    FolderMove(file, destFolderPath + Path.GetFileName(file));
                    Directory.Delete(file);
                }
                else
                {
                    if(FileExist(destFolderPath + Path.GetFileName(file)))
                    {
                        if(DeleteFile(destFolderPath + Path.GetFileName(file)))
                        {
                            File.Move(file, destFolderPath + Path.GetFileName(file));
                        }
                    }
                    else
                        File.Move(file, destFolderPath + Path.GetFileName(file));
                }
            }
            //Directory.Delete(srcFolderPath);
        }
    }
}
